/**
 * @file 日程日历组件
 * @date 2025/11/20
 * @author lyqjob@yeah.net
 */

import React, { useState, useEffect, useMemo, useCallback, useDeferredValue } from 'react';
import dayjs from 'dayjs';
import { Calendar, Modal, Form, Input, Button, List, Tag, message, Space, Select, Card, Badge, ConfigProvider, Row, Col, Drawer, TimePicker, Switch, DatePicker } from 'antd';
import { CalendarOutlined, ArrowUpOutlined, ArrowDownOutlined ,FullscreenOutlined ,FullscreenExitOutlined, LeftOutlined, RightOutlined, ExpandOutlined } from '@ant-design/icons';
import zhCN from 'antd/locale/zh_CN.js';
import styles from './index.less';

const ScheduleCalendar = () => {
    // 日程相关状态
    const [schedules, setSchedules] = useState([]);
    const [drawerVisible, setDrawerVisible] = useState(false); // 统一使用Drawer
    const [drawerMode, setDrawerMode] = useState('view'); // 'view' 或 'add'
    const [selectedDate, setSelectedDate] = useState(null);
    const [isExpanded, setIsExpanded] = useState(false);
    const [calendarMode, setCalendarMode] = useState('month'); // 控制展开/收起状态
    const [isAllDay, setIsAllDay] = useState(false); // 控制是否全天
    const [isMonthView, setIsMonthView] = useState(false); // 控制是否为月份视图
    const [form] = Form.useForm();

    // 计算属性：根据selectedDate动态计算当日程，避免状态冗余
    const deferredSchedules = useDeferredValue(schedules);
    const selectedDateSchedules = useMemo(() => {
        if (!selectedDate) return [];
        
        // 使用isMonthView状态来判断是否显示月份日程
        if (isMonthView) {
            // 显示该月的所有日程
            const monthStr = selectedDate.format('YYYY-MM');
            return deferredSchedules.filter(schedule => schedule.date.startsWith(monthStr));
        } else {
            // 显示该日期的日程
            const dateStr = selectedDate.format('YYYY-MM-DD');
            return deferredSchedules.filter(schedule => schedule.date === dateStr);
        }
    }, [deferredSchedules, selectedDate, isMonthView]);

    useEffect(() => {
        // 初始化一些模拟数据
        const mockSchedules = [
            {
                id: '1',
                date: dayjs().format('YYYY-MM-DD'),
                title: '团队会议',
                description: '讨论项目进展',
                time: '10:00',
                priority: 'high',
                completed: false
            },
            {
                id: '2',
                date: dayjs().format('YYYY-MM-DD'),
                title: '代码审查',
                description: '审查新功能代码',
                time: '14:00',
                priority: 'medium',
                completed: true
            },
            {
                id: '3',
                date: dayjs().add(1, 'day').format('YYYY-MM-DD'),
                title: '客户演示',
                description: '产品功能演示',
                time: '15:30',
                priority: 'high',
                completed: false
            },
            {
                id: '4',
                date: dayjs().add(2, 'day').format('YYYY-MM-DD'),
                title: '文档编写',
                description: '更新API文档',
                time: '09:00',
                priority: 'low',
                completed: false
            }
        ];
        setSchedules(mockSchedules);
    }, []);

    // 日程管理函数
    const handleAddSchedule = (values) => {
        let timeText = '全天';
        if (!isAllDay && values.startTime && values.endTime) {
            const startTime = dayjs(values.startTime).format('HH:mm');
            const endTime = dayjs(values.endTime).format('HH:mm');
            timeText = `${startTime}-${endTime}`;
        }
        
        // 确定日期：如果选择了具体日期就使用选择的日期，否则使用selectedDate
        const scheduleDate = values.scheduleDate || selectedDate.format('YYYY-MM-DD');
        
        const newSchedule = {
            id: Date.now().toString(),
            date: scheduleDate,
            title: values.title,
            description: values.description,
            time: timeText,
            priority: values.priority || 'medium',
            completed: false
        };
        setSchedules([...schedules, newSchedule]);
        setDrawerVisible(false);
        setDrawerMode('view');
        setIsAllDay(false);
        form.resetFields();
        message.success('日程添加成功！');
    };

    const handleDateClick = (date) => {
        setSelectedDate(date);
        setIsMonthView(false); // 设置为日期视图
        setDrawerMode('view');
        setDrawerVisible(true);
    };

    // 新增：处理月份点击的函数
    const handleMonthClick = (date) => {
        // 设置为该月的第一天
        const firstDayOfMonth = date.startOf('month');
        setSelectedDate(firstDayOfMonth);
        setIsMonthView(true); // 设置为月份视图
        setDrawerMode('view');
        setDrawerVisible(true);
    };

    // 新增：直接添加日程的函数
    const handleQuickAddSchedule = (date) => {
        setSelectedDate(date);
        setIsMonthView(false); // 设置为日期视图
        setDrawerMode('add');
        setDrawerVisible(true);
    };

    const handleDeleteSchedule = useCallback((scheduleId) => {
        setSchedules(prev => prev.filter(schedule => schedule.id !== scheduleId));
    }, []);

    const handleToggleComplete = (scheduleId) => {
        const updatedSchedules = schedules.map(schedule => 
            schedule.id === scheduleId ? { ...schedule, completed: !schedule.completed } : schedule
        );
        setSchedules(updatedSchedules);
    };

    const getPriorityColor = (priority) => {
        switch(priority) {
            case 'high': return 'red';
            case 'medium': return 'orange';
            case 'low': return 'green';
            default: return 'blue';
        }
    };

    // 自定义单元格渲染
    const cellRender = (current, info) => {
        if (info.type === 'date') {
            return dateCellRender(current);
        }
        if (info.type === 'month') {
            return monthCellRender(current);
        }
        return info.originNode;
    };

    // 自定义月份单元格渲染
    const monthCellRender = (value) => {
        const monthSchedules = deferredSchedules.filter(schedule => schedule.date.startsWith(value.format('YYYY-MM')));
        const hasCompletedSchedules = monthSchedules.some(schedule => schedule.completed);
        const hasIncompleteSchedules = monthSchedules.some(schedule => !schedule.completed);
        
        let badgeStatus = 'processing'; // 默认蓝色
        if (hasCompletedSchedules && !hasIncompleteSchedules) {
            badgeStatus = 'success'; // 全部完成 - 绿色
        } else if (!hasCompletedSchedules && hasIncompleteSchedules) {
            badgeStatus = 'warning'; // 全部未完成 - 橙色
        } else if (hasCompletedSchedules && hasIncompleteSchedules) {
            badgeStatus = 'error'; // 部分完成 - 红色
        }
        
        return (
            <div 
                className={styles.scheduleIndicator}
                onClick={() => handleMonthClick(value)}
                style={{ 
                    cursor: 'pointer',
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    alignItems: 'flex-start',
                    justifyContent: 'flex-end'
                }}
            >
                <Badge 
                    status={badgeStatus} 
                    style={{ 
                        marginLeft: '4px',
                        marginTop: '2px'
                    }}
                />
            </div>
        );
    };

    // 自定义日期单元格渲染
    const dateCellRender = (value) => {
        const dateStr = value.format('YYYY-MM-DD');
        const daySchedules = deferredSchedules.filter(schedule => schedule.date === dateStr);
        
        // 如果没有日程，返回空
        if (daySchedules.length === 0) {
            return null;
        }
        
        // 小日历永远只显示点
        const hasCompletedSchedules = daySchedules.some(schedule => schedule.completed);
        const hasIncompleteSchedules = daySchedules.some(schedule => !schedule.completed);
        
        let badgeStatus = 'processing'; // 默认蓝色
        if (hasCompletedSchedules && !hasIncompleteSchedules) {
            badgeStatus = 'success'; // 全部完成 - 绿色
        } else if (!hasCompletedSchedules && hasIncompleteSchedules) {
            badgeStatus = 'warning'; // 全部未完成 - 橙色
        } else if (hasCompletedSchedules && hasIncompleteSchedules) {
            badgeStatus = 'error'; // 部分完成 - 红色
        }
        
        return (
            <div className={styles.scheduleIndicator}>
                <Badge 
                    status={badgeStatus} 
                    style={{ 
                        marginLeft: '4px',
                        marginTop: '2px'
                    }}
                />
            </div>
        );
    };

    // Modal中大日历的详细渲染
    const modalDateCellRender = (value) => {
        const dateStr = value.format('YYYY-MM-DD');
        const daySchedules = deferredSchedules.filter(schedule => schedule.date === dateStr);
        
        // 如果没有日程，返回空
        if (daySchedules.length === 0) {
            return null;
        }
        
        // 大日历永远显示详细的块状标签
        return (
            <div className={styles.scheduleList}>
                {daySchedules.slice(0, 3).map(schedule => {
                    // 为每个日程计算Badge状态
                    let badgeStatus = 'processing'; // 默认蓝色
                    if (schedule.completed) {
                        badgeStatus = 'success'; // 已完成 - 绿色
                    } else if (schedule.priority === 'high') {
                        badgeStatus = 'error'; // 高优先级未完成 - 红色
                    } else if (schedule.priority === 'medium') {
                        badgeStatus = 'warning'; // 中优先级未完成 - 橙色
                    } else {
                        badgeStatus = 'processing'; // 低优先级未完成 - 蓝色
                    }
                    
                    return (
                        <div 
                            key={schedule.id} 
                            className={`${styles.scheduleTag} ${schedule.completed ? styles.completed : styles[schedule.priority]}`}
                            title={`${schedule.title} - ${schedule.time}`}
                        >
                            <Badge 
                                status={badgeStatus} 
                                style={{ 
                                    marginRight: '4px',
                                    marginTop: '2px'
                                }}
                            />
                            {schedule.time && `${schedule.time} `}
                            {schedule.title.length > 10 ? schedule.title.substring(0, 10) + '...' : schedule.title}
                        </div>
                    );
                })}
                {daySchedules.length > 3 && (
                    <div className={styles.moreSchedules}>
                        +{daySchedules.length - 3} 更多
                    </div>
                )}
            </div>
        );
    };

    // 统一的日程Drawer - 支持查看和添加模式
    const ScheduleDrawer = () => {
        const handleClose = () => {
            setDrawerVisible(false);
            setDrawerMode('view');
            setIsMonthView(false); // 重置月份视图状态
            form.resetFields();
        };

        const handleSwitchToAdd = () => {
            setDrawerMode('add');
        };

        const handleSwitchToView = () => {
            setDrawerMode('view');
            setIsAllDay(false);
            form.resetFields();
        };

        // 判断是否是月份视图
        const titleText = selectedDate ? (
            isMonthView ? selectedDate.format('YYYY年MM月') : selectedDate.format('YYYY-MM-DD')
        ) : '';

        return (
            <Drawer
                title={
                    drawerMode === 'add' ? (
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <span>添加日程 - {titleText}</span>
                            <Button size="small" onClick={handleSwitchToView}>
                                返回列表
                            </Button>
                        </div>
                    ) : (
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <span>日程列表 - {titleText}</span>
                            <Button 
                                type="primary" 
                                size="small"
                                onClick={handleSwitchToAdd}
                            >
                                添加日程
                            </Button>
                        </div>
                    )
                }
                placement="right"
                width={500}
                open={drawerVisible}
                onClose={handleClose}
                motion={false}
            >
                {drawerMode === 'add' ? (
                    // 添加日程表单
                    <Form
                        form={form}
                        layout="vertical"
                        onFinish={handleAddSchedule}
                    >
                        <Form.Item
                            name="title"
                            label="日程标题"
                            rules={[{ required: true, message: '请输入日程标题' }]}
                        >
                            <Input placeholder="请输入日程标题" />
                        </Form.Item>
                        
                        {/* 如果是月份视图，显示日期选择器 */}
                        {isMonthView && (
                            <Form.Item
                                name="scheduleDate"
                                label="选择日期"
                                rules={[{ required: true, message: '请选择具体日期' }]}
                                initialValue={selectedDate}
                            >
                                <DatePicker 
                                    format="YYYY-MM-DD"
                                    placeholder="请选择日期"
                                    style={{ width: '100%' }}
                                />
                            </Form.Item>
                        )}
                        
                        <Form.Item
                            name="time"
                            label="时间"
                        >
                            <Space direction="vertical" style={{ width: '100%' }}>
                                <Form.Item name="allDay" noStyle>
                                    <Switch 
                                        checkedChildren="全天" 
                                        unCheckedChildren="指定时间" 
                                        checked={isAllDay}
                                        onChange={setIsAllDay}
                                    />
                                </Form.Item>
                                {!isAllDay && (
                                    <Space.Compact style={{ width: '100%' }}>
                                        <Form.Item name="startTime" noStyle>
                                            <TimePicker 
                                                format="HH:mm"
                                                placeholder="开始时间"
                                                style={{ width: '50%' }}
                                            />
                                        </Form.Item>
                                        <Form.Item name="endTime" noStyle>
                                            <TimePicker 
                                                format="HH:mm"
                                                placeholder="结束时间"
                                                style={{ width: '50%' }}
                                            />
                                        </Form.Item>
                                    </Space.Compact>
                                )}
                            </Space>
                        </Form.Item>
                        
                        <Form.Item
                            name="priority"
                            label="优先级"
                            initialValue="medium"
                        >
                            <Select>
                                <Select.Option value="high">高</Select.Option>
                                <Select.Option value="medium">中</Select.Option>
                                <Select.Option value="low">低</Select.Option>
                            </Select>
                        </Form.Item>
                        
                        <Form.Item
                            name="description"
                            label="描述"
                        >
                            <Input.TextArea rows={3} placeholder="请输入日程描述" />
                        </Form.Item>
                        
                        <Form.Item>
                            <Space>
                                <Button type="primary" htmlType="submit">
                                    添加
                                </Button>
                                <Button onClick={handleSwitchToView}>
                                    取消
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                ) : (
                    // 查看日程列表
                    <div style={{ height: '70vh', overflow: 'auto' }}>
                        {selectedDateSchedules.length > 0 ? (
                            <List
                                itemLayout="horizontal"
                                split={false}
                                rowKey="id"
                                dataSource={selectedDateSchedules}
                                renderItem={(schedule) => (
                                    <List.Item
                                        actions={[
                                            <Button 
                                                key="complete" 
                                                type="link" 
                                                onClick={() => handleToggleComplete(schedule.id)}
                                            >
                                                {schedule.completed ? '标记未完成' : '标记完成'}
                                            </Button>,
                                            <Button 
                                                key="delete" 
                                                type="link" 
                                                danger 
                                                onClick={() => handleDeleteSchedule(schedule.id)}
                                            >
                                                删除
                                            </Button>
                                        ]}
                                    >
                                        <List.Item.Meta
                                            title={
                                                <Space>
                                                    <span style={{ textDecoration: schedule.completed ? 'line-through' : 'none' }}>
                                                        {schedule.title}
                                                    </span>
                                                    <Tag color={getPriorityColor(schedule.priority)} size="small">
                                                        {schedule.priority === 'high' ? '高' : schedule.priority === 'medium' ? '中' : '低'}
                                                    </Tag>
                                                    {schedule.completed && <Tag color="green">已完成</Tag>}
                                                </Space>
                                            }
                                            description={
                                                <div>
                                                    <div style={{ marginBottom: '4px' }}>
                                                        <strong>时间：</strong>{schedule.time}
                                                    </div>
                                                    {schedule.description && (
                                                        <div>
                                                            <strong>描述：</strong>{schedule.description}
                                                        </div>
                                                    )}
                                                </div>
                                            }
                                        />
                                    </List.Item>
                                )}
                            />
                        ) : (
                            <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                                该日期暂无日程
                            </div>
                        )}
                    </div>
                )}
            </Drawer>
        );
    };

    return (
        <>
            <Card 
                title={
                    <Space>
                        <CalendarOutlined />
                        <span>日程安排</span>
                    </Space>
                }
                extra={
                    <Space>
                        <Button 
                            type="text" 
                            onClick={() => setCalendarMode(calendarMode === 'year' ? 'month' : 'year')}
                            title={calendarMode === 'year' ? "切换到月视图" : "切换到年视图"}
                        >
                            {calendarMode === 'year' ? '年视图' : '月视图'}
                        </Button>
                        <Button 
                            type="text" 
                            onClick={() => setIsExpanded(!isExpanded)}
                            title={isExpanded ? "收起详情" : "展开详情"}
                        >
                            {isExpanded ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                        </Button>
                    </Space>
                }
            >
                <ConfigProvider locale={zhCN} >
                    <Calendar 
                        cellRender={cellRender}
                        onSelect={(date, { source }) => {
                            console.log(source, "onSelect");
                            if (source === 'date') {
                                handleDateClick(date);
                            } else if (source === 'month') {
                                // 点击月份后自动切换回月视图
                                if (calendarMode === 'year') {
                                    handleMonthClick(date);
                                }
                                // handleMonthClick(date);
                                // 点击月份后自动切换回月视图
                                setCalendarMode('month');
                            }
                        }}
                        onPanelChange={(value, mode) => {
                            console.log(value, mode, "onPanelChange");
                            setCalendarMode(mode);
                        }}
                        mode={calendarMode}
                    />
                </ConfigProvider>
            </Card>
            
            {/* 统一的日程Drawer */}
            <ScheduleDrawer />
            <Modal 
                title={`日程安排 - ${selectedDate ? selectedDate.format('YYYY-MM-DD') : ''}`}
                open={isExpanded}
                onCancel={() => setIsExpanded(false)}
                footer={null}
                width={'100vw'}
                centered={true}
                style={{overflow: 'hidden'}}
            >
                <div style={{height: '80vh', overflow: 'auto'}}>
                    <ConfigProvider locale={zhCN} >
                        <Calendar 
                            fullscreen={true}
                            cellRender={(current, info) => {
                                if (info.type === 'date') {
                                    return modalDateCellRender(current);
                                }
                                if (info.type === 'month') {
                                    return monthCellRender(current);
                                }
                                return info.originNode;
                            }}
                            onSelect={handleDateClick}
                        />
                    </ConfigProvider>
                </div>
            </Modal>
            
        </>
    );
};

export default ScheduleCalendar;